package se.quiz.cliente;

import org.json.JSONException;
import org.json.JSONObject;

import se.quiz.cliente.R;
import se.quiz.bean.Usuario;
import se.quiz.cliente.conexao.HttpManager;
import se.quiz.cliente.conexao.PacoteRequisicao;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

public class Inicial extends Activity {
	
	public static String USUARIO = "";
	public static long IDUSUARIO = 0;
	public static int PONTOS = 0;
	public static Usuario usuario = null;
//	public static String ipServidor = "192.168.25.7";
	public static String ipServidor = "10.0.2.2";
	public static String portaServidor = "8080";
	
	
	private EditText etUsuario ;
	private EditText etSenha ;
	
	private Tarefa tarefa;
	
	private String autenticacao = null;
	
	private ProgressBar pb;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.inicial);
		
		pb = (ProgressBar) findViewById(R.id.pbInicial);
		pb.setVisibility(View.INVISIBLE);
		
		etUsuario = (EditText)findViewById(R.id.etUsuario);
		etSenha = (EditText)findViewById(R.id.etSenha);		
		etUsuario.requestFocus();

		
		Button btnEntrar = (Button) findViewById(R.id.btnEntrar);		
		btnEntrar.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				if(isOnline()){			
					String usuario = etUsuario.getText().toString();
					String senha = etSenha.getText().toString();
					if(usuario.length()<3 || senha.length()<3){
						Toast.makeText(getApplicationContext(), "Usuario ou senha devem conter pelo menos 3 caracteres", Toast.LENGTH_SHORT).show();
						etUsuario.setText("");
						etSenha.setText("");
						etUsuario.requestFocus();
					}else{	
						pb.setVisibility(View.VISIBLE);						
						tarefa = new Tarefa();
						PacoteRequisicao pacote = new PacoteRequisicao();
						pacote.setMethod("POST");

						pacote.setUri("http://"+ipServidor+":"+portaServidor+"/QuizServer/ServletLogin");

						pacote.setParametro("usuario", usuario);
						pacote.setParametro("senha", senha);
						tarefa.execute(pacote);			
					}
				}else{
					Toast.makeText(getApplicationContext(), "Rede nao disponivel", Toast.LENGTH_SHORT).show();
				}				
			}
		});
		
		
		Button btnCadastrarSe = (Button) findViewById(R.id.btnCadastrarSe);		
		btnCadastrarSe.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				startActivity(new Intent(Inicial.this, CadastrarSe.class));
			}
		});
	}
	protected boolean isOnline(){
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo netInfo = cm.getActiveNetworkInfo();
		if(netInfo != null && netInfo.isConnectedOrConnecting()){
			
			return true;
		}else{
			return false;
		}
	}
	
	private class Tarefa extends AsyncTask<PacoteRequisicao, String, String>{

		@Override
		protected void onPreExecute() {
		}
		
		@Override
		protected String doInBackground(PacoteRequisicao... params) {
			
			try {
				JSONObject json = new JSONObject(HttpManager.getData(params[0]));
				autenticacao = json.getString("message"); 
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}			
			return null;
		}
		
		@Override
		protected void onPostExecute(String result) {			
			pb.setVisibility(View.INVISIBLE);
				
			if(Boolean.parseBoolean(autenticacao)){
				startActivity(new Intent(Inicial.this, MenuPrincipal.class));
				Log.i("logquiz","iniciar");
			}else{
				Toast.makeText(getApplicationContext(), "Usuario ou senha incorretos", Toast.LENGTH_SHORT).show();
				etUsuario.setText("");
				etSenha.setText("");
				etUsuario.requestFocus();
			}			
		}
		
		@Override
		protected void onProgressUpdate(String... values) {
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.inicial, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}
